#!/usr/bin/python 
from BeautifulSoup import *
import os
import sys
import re
reload(sys)
sys.setdefaultencoding('utf-8') 

def extract_css(doc_base, node):
    try:
        if node['href'].find('ext-all') != -1 or node['href'].find('common.js') != -1:
            return ""
        else:
            node.extract()
            return get_content(doc_base, node['href'])
    except:
        if len(node.contents) == 1:
	        node.extract()
	        return node.contents[0]
        else:
            return ""

def extract_js(doc_base, node):
    try:
        if node['src'].find('ext-') != -1:
            doc.insert(len(doc.contents), node)
            return ""
        else:
            if not node['src'].endswith('.js'):
                return
            node.extract()
            return get_content(doc_base, node['src'])
    except:
        if len(node.contents) == 1:
            if node.contents[0].find('customCssContainer') == -1:
                node.extract()
                return node.contents[0]
            else:
               return ""
        else:
            return ""

def get_content(doc_base, path):
    #print('dir: '+doc_base+path)
    #print(os.path.exists(doc_base+path))
    #print(open(os.path.join(doc_base+path)).read())
    return open(os.path.join(doc_base+path)).read()

def write_content(doc_base, path, content):
    file = open(os.path.join(doc_base, path), "w")
    if isinstance(content, list):
        for line in content:
            if line is not None:
                file.write(line)
                file.write("\n")
    else:
        file.write(content)
    file.close()

def handle_doc(rootbase,doc_base, file):
    file_base_name = os.path.splitext(file)[0]
         
    content = open(os.path.join(doc_base, file)).read()
    doc = BeautifulSoup(content)
    #print('doc: '+str(doc))
    if doc.html:  
        scripts = doc.html.findAll('script')
	#print('scripts.length: '+str(len(scripts)))
        js = [extract_js(rootbase, script) for script in scripts]
        #print('js.length: '+str(len(js)))
	#print('js[0]: '+js[0])
        if len(js) != 0:
            script = Tag(doc, 'script')
            script['type'] = 'text/javascript'
            script['src'] = '%s_all.js' % file_base_name
	    head = Tag(doc,'head')
            doc.insert(len(doc.contents), script)
	    #head.insert(len(head.contents), script)
            write_content(doc_base, '%s_all.js' % file_base_name, js)
            write_content(doc_base, '%s' % file, doc.prettify())
            print "Finish Merging File [%s] " % os.path.join(doc_base, file)

if __name__ == "__main__":    
    doc_base = sys.argv[1]
    #doc_base = r"C:\myspace\jade-soft\AntBuild\warsrc"
    #print('DOC_BASE'+doc_base)
    for dirpath, dirnames, filenames in os.walk(doc_base):
        for filename in filenames:
            if filename.endswith(".html"):
                handle_doc(doc_base,dirpath, filename)
